﻿using MediatR;
using Traceable.App.Application.Command.Goods;
using Traceable.App.DTOS;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Goods
{
    public class GoodsTraceableListHandler:IRequestHandler<GoodsTraceableListCommand, ApiPaging<GoodsTraceableDto>>
    {
        private readonly IBaseRepository<Goods_Table> _goodsRepository;
        private readonly IBaseRepository<Traceable_Table> _traceableRepository;

        public GoodsTraceableListHandler(IBaseRepository<Goods_Table> goodsRepository, IBaseRepository<Traceable_Table> traceableRepository)
        {
            _goodsRepository = goodsRepository;
            _traceableRepository = traceableRepository;
        }

        /// <summary>
        /// 商品溯源基本信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiPaging<GoodsTraceableDto>> Handle(GoodsTraceableListCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<GoodsTraceableDto>result = new ApiPaging<GoodsTraceableDto>();

            var goods = _goodsRepository.GetAll();
            var traceable = _traceableRepository.GetAll().Where(p=>p.IsDelete==false);

            if(!string.IsNullOrEmpty(request.GoodsName))
            {
                goods = goods.Where(p => p.GoodsName.Contains(request.GoodsName));
            }
            if (!string.IsNullOrEmpty(request.Batch))
            {
                goods = goods.Where(p => p.GoodsName.Contains(request.GoodsName));
            }

            var list = from t in traceable
                       join g in goods on t.GoodsId equals g.Id
                       select new GoodsTraceableDto
                       {
                           Id = t.Id,
                           GoodsId = g.Id,
                           GoodsName=g.GoodsName,
                           Batch=t.Batch,
                           Expiration=t.Expiration,
                           Permit=t.Permit,
                           Companies=t.Companies,
                           Perfect=t.Perfect,
                           Cover=t.Cover,
                           CreateTime=t.CreateTime,
                           Creater=t.Creater,
                           UpdateTime=t.UpdateTime,
                           Updater=t.Updater

                       };

            result.TotalCount = list.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.pagesize);
            result.Code = StatusEnum.OK;
            result.PagData=list.OrderByDescending(c=>c.Id).Skip((request.pageindex-1)*request.pagesize).Take(request.pagesize).ToList();
            result.Message = "查询成功";
            return Task.FromResult(result);
        }

    }
}
